//The MIT License

//Copyright (c) 2010 Nick Darnell

//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
using System.Text;

namespace Polymorph.Test
{
    public class Forger
    {
        public static GetDelegate GetGetDelegate(Type objectType, string memberName)
        {
            PropertyInfo pi = objectType.GetProperty(memberName);
            if (pi != null)
            {
                return CreateGetDelegate(objectType, memberName, pi);
            }

            FieldInfo fi = objectType.GetField(memberName);
            if (fi != null)
            {
                return CreateGetDelegate(objectType, memberName, fi);
            }

            throw new Exception(String.Format(
                "Member: '{0}' is not a Property or Field of Type: '{1}'",
                memberName, objectType.Name));
        }

        public static SetDelegate GetSetDelegate(Type objectType, string memberName)
        {
            PropertyInfo pi = objectType.GetProperty(memberName);
            if (pi != null)
            {
                return CreateSetDelegate(objectType, memberName, pi);
            }

            FieldInfo fi = objectType.GetField(memberName);
            if (fi != null)
            {
                return CreateSetDelegate(objectType, memberName, fi);
            }

            throw new Exception(String.Format(
                "Member: '{0}' is not a Property or Field of Type: '{1}'",
                memberName, objectType.Name));
        }

        public static ForgeLink GetLink(Type objectType, string memberName)
        {
            PropertyInfo pi = objectType.GetProperty(memberName);
            if (pi != null)
            {
                ForgeLink link = new ForgeLink();
                link.SystemType = pi.PropertyType;
                link.Get = CreateGetDelegate(objectType, memberName, pi);
                link.Set = CreateSetDelegate(objectType, memberName, pi);

                return link;
            }

            FieldInfo fi = objectType.GetField(memberName);
            if (fi != null)
            {
                ForgeLink link = new ForgeLink();
                link.SystemType = fi.FieldType;
                link.Get = CreateGetDelegate(objectType, memberName, fi);
                link.Set = CreateSetDelegate(objectType, memberName, fi);

                return link;
            }

            throw new Exception(String.Format(
                "Member: '{0}' is not a Property or Field of Type: '{1}'",
                memberName, objectType.Name));
        }

        #region Create GetDelegate

        internal static GetDelegate CreateGetDelegate(Type objectType, string memberName, FieldInfo fi)
        {
            CodeDynamicMethod method = new CodeDynamicMethod(objectType, "get_" + memberName, typeof(object), new Type[] { typeof(object) }, true);
            CodeBuilder cd = method.CodeBuilder;

            cd.Return(method.GetArg(0).CastTo(objectType)[fi]);

            return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate));
        }

        internal static GetDelegate CreateGetDelegate(Type objectType, string memberName, PropertyInfo pi)
        {
            if (!pi.CanRead)
                return null;

            CodeDynamicMethod method = new CodeDynamicMethod(objectType, "get_" + memberName, typeof(object), new Type[] { typeof(object) }, true);
            CodeBuilder cd = method.CodeBuilder;

            cd.Return(method.GetArg(0).CastTo(objectType)[pi]);

            return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate));
        }

        #endregion

        #region Create SetDelegate

        internal static SetDelegate CreateSetDelegate(Type objectType, string memberName, FieldInfo fi)
        {
            CodeDynamicMethod method = new CodeDynamicMethod(objectType, "set_" + memberName, typeof(void), new Type[] { typeof(object), typeof(object) }, true);
            CodeBuilder cd = method.CodeBuilder;

            cd.Assign(method.GetArg(0).CastTo(objectType)[fi], method.GetArg(1).CastTo(fi.FieldType));

            return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate));
        }

        internal static SetDelegate CreateSetDelegate(Type objectType, string memberName, PropertyInfo pi)
        {
            if (!pi.CanWrite)
                return null;

            CodeDynamicMethod method = new CodeDynamicMethod(objectType, "set_" + memberName, typeof(void), new Type[] { typeof(object), typeof(object) }, true);
            CodeBuilder cd = method.CodeBuilder;
            
            cd.Assign(method.GetArg(0).CastTo(objectType)[pi], method.GetArg(1).CastTo(pi.PropertyType));

            return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate));
        }

        #endregion
    }
}
